<template>
	<!-- 服务商详情 -->
	<view class="service-provider-details" :class="{'no-scroll': isPopupShow}" :safe-area-inset-bottom="false">
		<!-- 企业图片展示区 -->
		<view class="company-banner">
			<image :src="detailInfo.qyjjXp" mode="aspectFill"></image>
			<!-- 		<swiper class="swiper" circular autoplay interval="3000">
				<swiper-item>
					
				</swiper-item>
			</swiper> -->
		</view>

		<!-- 企业信息卡片 -->
		<view class="company-info">
			<view class="info-card">
				<!-- 发布信息 -->
				<view class="publish-info">
					<view class="left">
						<text class="platform">超享圈</text>
						<text class="date">{{ detailInfo.createTimeCn }}发布</text>
					</view>
					<view v-if="guid !== null" class="right">
						<uni-icons type="eye" size="14"></uni-icons>
						<text>{{ detailInfo.xyyfServiceLookList? detailInfo.xyyfServiceLookList.length:'0'  }}</text>
					</view>
				</view>

				<!-- 联系人信息 -->
				<view class="info-section">
					<view class="section-title">联系人信息</view>
					<view class="info-item">
						<text class="label">联系人</text>
						<text class="value">{{detailInfo.realName || '-'}}</text>
					</view>
					<view class="info-item">
						<text class="label">手机号</text>
						<text class="value"
							@click="handlePhoneClick">{{userInfo.userType === '普通用户' ? (showContactInfo ? detailInfo.telphone : maskPhone(detailInfo.telphone)) : detailInfo.telphone || '-'}}</text>
					</view>
					<view class="info-item">
						<text class="label">微信号</text>
						<text class="value"
							@click="handleWeixinClick">{{userInfo.userType === '普通用户' ? (showContactInfo ? detailInfo.weixin : maskWeixin(detailInfo.weixin)) : detailInfo.weixin || '-'}}</text>
					</view>
					<view v-if="userInfo.userType === '普通用户'" class="show-contact-btn" @click="handleShowContact">
						<text>{{showContactInfo ? '隐藏联系人信息' : '显示联系人完整信息'}}</text>
					</view>
				</view>

				<!-- 企业名称 -->
				<view v-if="detailInfo.companyName" class="info-section company-name-section">
					<view class="section-title">企业名称</view>
					<view class="section-content">{{detailInfo.companyName || '-'}}</view>
				</view>
				<!-- 企业需求描述 -->
				<view v-if="detailInfo.qyxqms" class="info-section company-name-section">
					<view class="section-title">企业需求描述</view>
					<view class="section-content">{{detailInfo.qyxqms || '-'}}</view>
				</view>

				<!-- 主营业务 -->
				<view v-if="detailInfo.zyyw" class="info-section">
					<view class="section-title">主营业务</view>
					<view class="section-content">{{detailInfo.zyyw || '-'}}</view>
				</view>

				<!-- 企业介绍 -->
				<view v-if="detailInfo.qyjj" class="info-section">
					<view class="section-title">企业介绍</view>
					<view class="section-content">{{detailInfo.qyjj || '-'}}</view>
				</view>
				<!-- 服务范围 -->
				<view v-if="detailInfo.serviceScope && detailInfo.serviceScope.length > 0" class="info-section">
					<view class="section-title">服务范围</view>
					<view class="service-scope">
						<text v-for="(item, index) in detailInfo.serviceScope" :key="index"
							class="scope-item">{{item}}</text>
					</view>
				</view>
				<!-- 资质证明 -->
				<view v-if="detailInfo.zzzmList && detailInfo.zzzmList.length > 0" class="info-section">
					<view class="section-title">产品图片</view>
					<view class="cert-image">
						<image v-for="(item, index) in detailInfo.zzzmList" :key="index" :src="item" mode="widthFix"
							@click="previewImage(index)"></image>
					</view>
				</view>


				<!-- 培训机构 -->
				<view v-if="detailInfo.peixunCompany" class="info-section">
					<view class="section-title">培训机构</view>
					<view class="section-content">{{detailInfo.peixunCompany || '-'}}</view>
				</view>
				<!-- 主题 -->
				<view v-if="detailInfo.peixunTitle" class="info-section">
					<view class="section-title">主题</view>
					<view class="section-content">{{detailInfo.peixunTitle || '-'}}</view>
				</view>

				<!-- 内容 -->
				<view v-if="detailInfo.peixunInfo" class="info-section">
					<view class="section-title">内容</view>
					<view class="section-content">{{detailInfo.peixunInfo || '-'}}</view>
				</view>

			</view>
		</view>

		<!-- 底部操作栏 -->
		<view v-if="guid !== null" class="footer-action">
			<view class="action-item" @click="handleLike">
				<uni-icons type="hand-up-filled" size="24" :color="isLiked ? '#AC6C17' : '#333'"></uni-icons>
				<text :class="{'active': isLiked}">{{likeCount}}</text>
			</view>
			<view class="action-item" @click="showCommentPopup">
				<uni-icons type="chat" size="24" :color="isCommented ? '#AC6C17' : '#333'"></uni-icons>
				<text :class="{'active': isCommented}">{{commentCount}}</text>
			</view>
		</view>

		<!-- 评论弹出层 -->
		<uni-popup ref="commentPopup" type="bottom" @change="handlePopupChange" :mask-click="true">
			<view class="comment-popup" :style="{ height: popupHeight + 'px' }">
				<!-- 添加评论列表区域 -->
				<scroll-view v-if="commentList.length > 0" scroll-y class="comment-list"
					:style="{ height: scrollViewHeight + 'px' }">
					<view class="comment-item" v-for="(item, index) in commentList" :key="index">
						<!-- 左侧头像 -->
						<image class="avatar" :src="item.member.avatar || '/static/images/head_default.png'"
							mode="aspectFill">
						</image>

						<!-- 中间内容区 -->
						<view class="content-wrap">
							<view class="user-info">
								<text class="name">{{item.member.realName || '无名'}}</text>
								<text class="time">{{formatTime(item.createTime)}}</text>
							</view>
							<view class="content">{{item.commentInfo}}</view>
						</view>
					</view>
				</scroll-view>
				<!-- 评论输入区域 -->
				<view class="comment-input-wrap">
					<textarea v-model="commentContent" class="comment-input" placeholder="请输入评论内容"
						:adjust-position="true" :cursor-spacing="20" :show-confirm-bar="false" :focus="inputFocus"
						@focus="onInputFocus" @blur="onInputBlur">
					</textarea>
					<button class="submit-btn" @click="submitComment">发表评论</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		parseDate
	} from '@/utils/date.js';

	export default {
		data() {
			return {
				guid: null, // 服务商ID
				peixunTitle: '', // 培训信息
				detailInfo: {}, // 详情数据
				isLiked: false,
				likeCount: 0,
				commentCount: 0,
				commentContent: '',
				pageTitle: '', // 添加页面标题变量
				commentList: [], // 评论列表数据
				isPopupShow: false, // 添加弹窗显示状态
				isCommented: false, // 添加是否评论过的状态
				showContactInfo: false, // 是否显示完整联系人信息
				popupHeight: 600, // 弹窗默认高度
				scrollViewHeight: 400, // 滚动区域默认高度
				inputFocus: false, // 输入框焦点状态
				keyboardHeight: 0, // 键盘高度
			}
		},
		computed: {
			userInfo() {
				console.log(this.$store.state.user.userInfo)
				return this.$store.state.user.userInfo;
			}
		},
		onLoad(options) {
			// 服务商
			if (options.guid) {
				this.guid = options.guid;
				this.getDetails();
				this.initLook(options.guid) // 预览创建
				// 初始化点赞和评论数据
				this.initDz();
				this.initPl();
			}
			// 培训信息
			if (options.peixunTitle) {
				this.peixunTitle = options.peixunTitle;
				this.getPeixunList();
			}
			// 设置页面标题，去掉多余的引号
			if (options.text) {
				this.pageTitle = options.text.replace(/['"]/g, ''); // 移除所有引号
				uni.setNavigationBarTitle({
					title: this.pageTitle
				});
			}

		},
		methods: {
			// 预览创建
			async initLook(id) {
				const requestData = {
					guid: id,
					serviceId: id,
					lookUserId: this.$store.state.user.userInfo.guid
				};
				const res = await this.$api.infoCustomCreateLook(requestData);
			},
			// 获取服务商详情
			async getDetails() {
				try {
					const params = {
						guid: this.guid
					}
					const res = await this.$api.getSwsListDetails(params);
					if (res.code === 200) {
						this.detailInfo = res.data;
					} else {
						uni.showToast({
							title: res.message || '获取详情失败',
							icon: 'none'
						});
					}
				} catch (e) {
					uni.showToast({
						title: '网络异常，请稍后重试',
						icon: 'none'
					});
				}
			},
			// 获取培训信息详情
			async getPeixunList() {
				try {
					const params = {
						peixunTitle: this.peixunTitle
					}
					const res = await this.$api.getPeixunList(params)
					if (res.succ) {
						this.detailInfo = res.data[0];
						this.detailInfo.realName = res.data[0].peixunLianxiren
						this.detailInfo.telphone = res.data[0].peixunShoujihao
						this.detailInfo.weixin = res.data[0].peixunWeixin
						this.detailInfo.qyjjXp = res.data[0].peixunTp
					}
				} catch (error) {
					console.error('获取培训信息失败:', error)
				}
			},

			// 初始化互动数据
			initInteractionData() {
				// 这里可以添加获取点赞和评论数量的接口调用
				this.likeCount = 0;
				this.commentCount = 0;
			},
			// 初始化点赞信息
			async initDz() {
				const data = {
					releaseId: this.guid // 文章id
				};
				const res = await this.$api.getReleaseDzInfo(data);
				if (res.succ) {
					this.likeCount = res.data.length;
					// 判断当前用户是否已点赞
					const currentUserId = this.$store.state.user.userInfo.guid;
					this.isLiked = res.data.some(item => item.dzUserId === currentUserId);
				}

			},
			// 处理点赞
			async handleLike() {
				const data = {
					releaseId: this.guid, // 文章id
					dzUserId: this.$store.state.user.userInfo.guid, // 点赞人的id
				};
				try {
					let res;
					if (this.isLiked) {
						// 如果已点赞，则取消点赞
						res = await this.$api.deleteReleaseDz(data);
					} else {
						// 如果未点赞，则添加点赞
						res = await this.$api.getReleaseDz(data);
					}

					if (res.succ) {
						// 更新点赞状态和数量
						this.isLiked = !this.isLiked;
						this.initDz()

						uni.showToast({
							title: this.isLiked ? '点赞成功' : '点赞取消成功',
							icon: 'success'
						});
					}
				} catch (e) {
					uni.showToast({
						title: '操作失败，请稍后重试',
						icon: 'none'
					});
				}
			},
			// 初始化评论信息
			async initPl() {
				const data = {
					releaseId: this.guid
				};
				const res = await this.$api.getReleaseCommentInfo(data);
				if (res.succ) {
					this.commentCount = res.data.length;
					// 判断当前用户是否评论过
					const currentUserId = this.$store.state.user.userInfo.guid;
					this.isCommented = res.data.some(item => item.createUserId === currentUserId);

					// 对评论列表按时间倒序排序
					this.commentList = res.data.sort((a, b) => {
						return new Date(b.createTime) - new Date(a.createTime);
					});
				}
			},

			// 显示评论弹窗
			showCommentPopup() {
				this.isPopupShow = true;
				// 使用uni-app的API来设置页面滚动
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 0
				});
				this.$refs.commentPopup.open();
			},

			// 关闭评论弹窗
			closeCommentPopup() {
				this.isPopupShow = false;
				this.$refs.commentPopup.close();
			},

			// 修改提交评论方法
			async submitComment() {
				if (!this.commentContent.trim()) {
					uni.showToast({
						title: '请输入评论内容',
						icon: 'none'
					});
					return;
				}
				const data = {
					releaseId: this.guid,
					commentInfo: this.commentContent,
					createUserId: this.$store.state.user.userInfo.guid,
				}

				const res = await this.$api.getReleaseComment(data);
				if (res.succ) {
					this.isCommented = true; // 评论成功后更新状态
					this.initPl(); // 刷新评论列表
					this.commentContent = '';
					this.closeCommentPopup();
					// this.getMsgCreate() // 评论成功后调用消息推送接口
					uni.showToast({
						title: '评论成功',
						icon: 'success'
					});
				}
			},
			// 评论成功后添加消息推送接口
			async getMsgCreate() {
				const data = {
					createUserId: this.$store.state.user.userInfo.guid, // 消息创建者用户id
					msgUserId: this.guid, // 消息接收者用户id
					msgType: '1', // 消息类型 0:关注 1:评论
					msgCn: this.pageTitle, // 消息内容
					msgJumpId: this.detailInfo.guid, // 消息跳转id:关注就是消息创建者id,评论就是文章id
				}
				const res = await this.$api.getMsgCreate(data);
			},

			// 添加时间格式化方法
			formatTime(timeStr) {
				if (!timeStr) return '';

				const date = parseDate(timeStr);
				if (isNaN(date.getTime())) return '';

				const now = new Date();
				const diff = now - date;

				// 小于1分钟
				if (diff < 60 * 1000) {
					return '刚刚';
				}
				// 小于1小时
				if (diff < 60 * 60 * 1000) {
					return Math.floor(diff / (60 * 1000)) + '分钟前';
				}
				// 小于24小时
				if (diff < 24 * 60 * 60 * 1000) {
					return Math.floor(diff / (60 * 60 * 1000)) + '小时前';
				}
				// 小于30天
				if (diff < 30 * 24 * 60 * 60 * 1000) {
					return Math.floor(diff / (24 * 60 * 60 * 1000)) + '天前';
				}

				// 超过30天，显示具体日期
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},

			// 处理评论点赞
			async handleCommentLike(item) {
				const data = {
					commentId: item.guid, // 评论id
					dzUserId: this.$store.state.user.userInfo.guid, // 点赞人的id
				};
				try {
					const res = await this.$api.getCommentDz(data);
					if (res.succ) {
						// 更新评论点赞状态
						item.isLiked = !item.isLiked;
						item.likeCount = item.isLiked ? (item.likeCount || 0) + 1 : (item.likeCount || 1) - 1;

						uni.showToast({
							title: item.isLiked ? '点赞成功' : '取消点赞',
							icon: 'success'
						});
					}
				} catch (e) {
					uni.showToast({
						title: '操作失败，请稍后重试',
						icon: 'none'
					});
				}
			},
			// 处理显示联系人信息
			async handleShowContact() {
				if (this.showContactInfo) {
					// 如果是显示状态，直接隐藏
					this.showContactInfo = false;
				} else {
					// 如果是隐藏状态，需要调用接口
					try {
						let data = {
							userId: this.$store.state.user.userInfo.guid
						}
						const res = await this.$api.getCheckPhone(data);
						if (res.succ) {
							this.showContactInfo = true;
						} else {
							uni.showToast({
								title: res.message || '今日次数已用完',
								icon: 'none'
							});
						}
					} catch (e) {
						uni.showToast({
							title: '网络异常，请稍后重试',
							icon: 'none'
						});
					}
				}
			},

			// 手机号掩码处理
			maskPhone(phone) {
				if (!phone) return '-';
				return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
			},

			// 微信号掩码处理
			maskWeixin(weixin) {
				if (!weixin) return '-';
				const length = weixin.length;
				if (length <= 2) return weixin;
				return weixin.charAt(0) + '*'.repeat(length - 2) + weixin.charAt(length - 1);
			},

			// 处理电话点击事件
			handlePhoneClick() {
				if (this.showContactInfo || this.userInfo.userType !== '普通用户') {
					if (this.detailInfo.telphone) {
						uni.makePhoneCall({
							phoneNumber: this.detailInfo.telphone,
							fail: (err) => {
								console.error('拨打电话失败:', err);
								uni.showToast({
									title: '拨打电话失败',
									icon: 'none'
								});
							}
						});
					}
				}
			},

			// 处理微信点击事件
			handleWeixinClick() {
				if (this.showContactInfo || this.userInfo.userType !== '普通用户') {
					if (this.detailInfo.weixin) {
						uni.setClipboardData({
							data: this.detailInfo.weixin,
							success: () => {
								uni.showToast({
									title: '微信号已复制',
									icon: 'success'
								});
							},
							fail: (err) => {
								console.error('复制微信号失败:', err);
								uni.showToast({
									title: '复制失败',
									icon: 'none'
								});
							}
						});
					}
				}
			},

			handlePopupChange(e) {
				if (e.show) {
					const windowHeight = uni.getSystemInfoSync().windowHeight;
					this.popupHeight = windowHeight * 0.8;
					this.scrollViewHeight = this.popupHeight - 280;
				}
			},

			// 处理输入框获得焦点
			onInputFocus(e) {
				this.inputFocus = true;
				// 获取键盘高度
				const keyboardHeight = e.detail.height || 0;
				this.keyboardHeight = keyboardHeight;

				// 计算弹窗和滚动区域的高度
				const windowHeight = uni.getSystemInfoSync().windowHeight;
				const popupHeight = windowHeight - keyboardHeight;
				this.popupHeight = popupHeight;

				// 计算评论列表的高度（减去输入区域的高度）
				this.scrollViewHeight = popupHeight - 280; // 280是输入区域的大致高度

				// 滚动到底部
				this.$nextTick(() => {
					if (this.commentList.length > 0) {
						const query = uni.createSelectorQuery().in(this);
						query.select('.comment-list').boundingClientRect(data => {
							if (data) {
								query.select('.comment-list').scrollOffset(res => {
									if (res) {
										uni.pageScrollTo({
											scrollTop: res.scrollHeight,
											duration: 0
										});
									}
								}).exec();
							}
						}).exec();
					}
				});
			},

			// 处理输入框失去焦点
			onInputBlur() {
				this.inputFocus = false;
				this.keyboardHeight = 0;
				this.popupHeight = 600;
				this.scrollViewHeight = 400;
			},

			// 预览图片
			previewImage(index) {
				uni.previewImage({
					current: index,
					urls: this.detailInfo.zzzmList,
					indicator: 'number',
					loop: true
				});
			},
		}
	}
</script>

<style lang="less" scoped>
	.service-provider-details {
		min-height: 100vh;
		background: linear-gradient(180deg, #FAEBDB 0%, rgba(255, 247, 238, 0) 400rpx);
		padding-bottom: 140rpx;
		padding-bottom: constant(safe-area-inset-bottom);
		/* iOS 11.2 */
		padding-bottom: env(safe-area-inset-bottom);
		/* iOS 11.2 */

		.company-banner {
			image {
				width: 100%;
				border-radius: 0 0 10rpx 10rpx;
			}

			.swiper {
				width: 100%;
				height: 100%;

				image {
					width: 100%;
					height: 100%;
					border-radius: 0 0 10rpx 10rpx;
				}
			}
		}

		.company-info {
			margin-top: -40rpx;
			position: relative;
			z-index: 1;

			.info-card {
				margin: 0 30rpx;
				background: #fff;
				border-radius: 20rpx;
				padding: 30rpx 30rpx 130rpx;
				box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

				.publish-info {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding-bottom: 20rpx;
					margin-bottom: 30rpx;
					border-bottom: 1rpx solid #eee;

					.left {
						.platform {
							color: #555;
							font-size: 26rpx;
							margin-right: 20rpx;
						}

						.date {
							color: #999;
							font-size: 24rpx;
						}
					}

					.right {
						display: flex;
						align-items: center;
						gap: 6rpx;
						color: #999;
						font-size: 24rpx;
					}
				}

				.info-section {
					margin-bottom: 40rpx;
					padding: 0 10rpx;

					.section-title {
						font-size: 34rpx;
						color: #222;
						margin-bottom: 24rpx;
						font-weight: bold;
						letter-spacing: 1rpx;
					}

					.info-item {
						display: flex;
						margin-bottom: 16rpx;
						font-size: 28rpx;
						line-height: 1.6;

						.label {
							width: 140rpx;
							color: #666;
						}

						.value {
							flex: 1;
							color: #333;
						}
					}

					.section-content {
						font-size: 28rpx;
						color: #333;
						line-height: 1.8;
					}

					.cert-image {
						image {
							width: 100%;
							border-radius: 8rpx;
							margin-bottom: 20rpx;
						}
					}
				}

				.company-name-section {
					.company-name {
						font-size: 32rpx;
						color: #333;
						font-weight: 500;
						padding: 24rpx;
						background: #f8f9fa;
						border-radius: 12rpx;
						text-align: center;
					}
				}
			}
		}

		.footer-action {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			height: 90rpx;
			background-color: #fff;
			display: flex;
			align-items: center;
			justify-content: space-around;
			padding-top: 15rpx;
			padding-bottom: 15rpx;
			box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
			z-index: 99;
			border-top: 1rpx solid #eee;
			padding-bottom: constant(safe-area-inset-bottom);
			/* iOS 11.2 */
			padding-bottom: env(safe-area-inset-bottom);
			/* iOS 11.2 */

			.action-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				padding: 8rpx 30rpx;

				text {
					font-size: 24rpx;
					color: #333;
					margin-top: 2rpx;
					line-height: 1;

					&.active {
						color: #AC6C17;
					}
				}
			}
		}

		&.no-scroll {
			height: 100vh;
			overflow: hidden;
		}
	}

	.comment-popup {
		background-color: #fff;
		position: relative;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;

		.comment-list {
			flex: 1;
			padding: 30rpx;
			box-sizing: border-box;

			.comment-item {
				display: flex;
				align-items: flex-start;
				padding: 24rpx 0;
				border-bottom: 1rpx solid #eee;

				&:last-child {
					border-bottom: none;
				}

				.avatar {
					width: 70rpx;
					height: 70rpx;
					border-radius: 50%;
					margin-right: 20rpx;
					background-color: #f5f5f5;
				}

				.content-wrap {
					flex: 1;
					margin-right: 20rpx;

					.user-info {
						display: flex;
						align-items: center;
						margin-bottom: 12rpx;

						.name {
							font-size: 28rpx;
							color: #222;
							font-weight: 600;
							margin-right: 16rpx;
						}

						.time {
							font-size: 24rpx;
							color: #999;
						}
					}

					.content {
						font-size: 28rpx;
						color: #333;
						line-height: 1.6;
						word-break: break-all;
					}
				}
			}
		}

		.comment-input-wrap {
			padding: 20rpx 30rpx;
			background-color: #fff;
			border-top: 1rpx solid #eee;

			.comment-input {
				width: 100%;
				height: 180rpx;
				background-color: #f5f5f5;
				border-radius: 12rpx;
				padding: 20rpx;
				font-size: 28rpx;
				box-sizing: border-box;
			}

			.submit-btn {
				margin-top: 20rpx;
				margin-bottom: env(safe-area-inset-bottom);
				background: linear-gradient(138deg, #F3B359 0%, #EC6A34 100%);
				color: #fff;
				font-size: 36rpx;
				height: 90rpx;
				line-height: 90rpx;
				border-radius: 45rpx;

				&:active {
					opacity: 0.8;
				}
			}
		}
	}

	.service-scope {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;

		.scope-item {
			padding: 10rpx 30rpx;
			background-color: #f5f7fa;
			color: #2b85e4;
			font-size: 26rpx;
			border-radius: 30rpx;
			white-space: nowrap;
		}
	}

	.show-contact-btn {
		display: flex;
		justify-content: flex-end;
		margin-top: 20rpx;

		text {
			padding: 12rpx 30rpx;
			background-color: #2b85e4;
			color: #fff;
			font-size: 26rpx;
			border-radius: 30rpx;
			transition: all 0.3s;

			&:active {
				opacity: 0.8;
			}
		}
	}
</style>